# zennotac-backend/app/services/pdf_processing.py

from pathlib import Path
from PyPDF2 import PdfReader, PdfWriter
from app.utils.filename_helper import generate_ocred_output_path
from typing import Callable, Optional


def process_pdf(
    input_path: str,
    suffix: str,
    page_transformer: Optional[Callable] = None,
    output_excel_path: Optional[str] = None  # <--- NEW
) -> str:       # don’t need this if using fixed filenames via output_excel_path.
    """
    Process a PDF file and optionally write to a fixed output path.

    Args:
        input_path: Path to the input PDF.
        suffix: Used to derive default output filename if output_excel_path not set.
        page_transformer: Optional page transformation function.
        output_excel_path: Optional fixed output path (e.g., 'autofill_input.xlsx').
    """
    input_pdf = Path(input_path)
    output_path = Path(output_excel_path) if output_excel_path else Path(generate_ocred_output_path(input_path, suffix))

    reader = PdfReader(str(input_pdf))
    writer = PdfWriter()

    for idx, page in enumerate(reader.pages):
        if page_transformer:
            page = page_transformer(page, idx)
        writer.add_page(page) 

    with open(output_path, 'wb') as f:
        writer.write(f)

    return str(output_path)


#  Example usage:
# # Scenario_1: Redact all page margins
# def redact_margins(page, page_number):
#     page.cropbox.upper_right = (page.cropbox.upper_right[0] - 50, page.cropbox.upper_right[1] - 50)
#     return page

# parse_redacted_text_file(input_path: str) -> str:
#     return process_pdf(input_path, suffix="_redacted", page_transformer=redact_margins)


# Scenario_2: Insert "Page X" watermark text
# def add_page_number(page, page_number):
#     page.add_annotation({
#         "Subtype": "/Text",
#         "Contents": f"Page {page_number + 1}"
#     })
#     return page

# parse_watermarked_file(input_path: str) -> str:
#     return process_pdf(input_path, suffix="_watermarked", page_transformer=add_page_number)

# Scenario_3: Rotate pages
# def rotate_pages(page, page_number):
#     page.rotate(90)  # Rotate all pages by 90 degrees
#     return page

# parse_rotated_file(input_path: str) -> str:
#     return process_pdf(input_path, suffix="_rotated", page_transformer=rotate_pages)